package net.gz01.wallet.web.controller.admin;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import net.gz01.util.ZODate;
import net.gz01.util.ZOMD5;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.Merch;
import net.gz01.wallet.web.model.MerchRole;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.service.Md5SaltUtil;

public class MerchUserController extends BaseController{

	public void search(){
		render("merch/merchUserList.html");
	}

	public void listJson(){
		Page<MerchUser> items = MerchUser.dao.search(super.getSearchCondition());
		renderJson(new PageRespon(items));
	}

	public void addPage(){
		setAttr("merchList", Merch.dao.selectToRedis());
		setAttr("roleList", MerchRole.dao.selectAll());
		render("merch/merchUserAdd.html");
	}

	public void updatePage(){
		MerchUser merchUser = MerchUser.dao.findById(getPara("id"));
		setAttr("merch", Merch.dao.selectByMerchCode(merchUser.getMerchCode()));
		setAttr("roleList", MerchRole.dao.selectAll());
		setAttr("item", merchUser);
		render("merch/merchUserUpdate.html");
	}

	@Before(Tx.class)
	public void add(){
		MerchUser merchUser = getModel(MerchUser.class,"item",true);
		if(MerchUser.dao.selectByUserName(merchUser.getUserName(), "1") != null){
			renderFail("用户名重复");
		}else{
			Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
			merchUser.setOrgCode(merch.getOrgCode());
			merchUser.setUpdateTime(ZODate.getDateTime());
			merchUser.setPassword(Md5SaltUtil.getEncryptedPwd(merchUser.getPassword()));
			merchUser.setPayPassword(merchUser.getPassword());
			merchUser.setEnable(true);
			merchUser.save();
			renderSuccess();
		}
	}

	public void update(){
		MerchUser merchUser = getModel(MerchUser.class,"item",true);
		String newPassword = getPara("newPassword");
		if(StrKit.notBlank(newPassword)){
			merchUser.setPassword(ZOMD5.codeFor(newPassword));
			merchUser.setPayPassword(ZOMD5.codeFor(newPassword));
		}
		merchUser.setUpdateTime(ZODate.getDateTime());
		merchUser.update();
		renderSuccess();
	}

	@Before(Tx.class)
	public void delete(){
		Integer id = getParaToInt("id");
		MerchUser.dao.deleteById(id);
		renderSuccess(false);
	}

	@Before(Tx.class)
	public void changeEnable(){
		MerchUser.dao.changeEnable(getParaToInt("id"));
		renderSuccess(false);
	}
}
